package io.gitee.kotle.player.ui.view.exo

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.databinding.ViewExoPlayerRootBinding
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.core.isPlaying
import io.gitee.kotle.player.core.retry
import io.gitee.kotle.player.ui.invisible
import io.gitee.kotle.player.ui.visible
import kotlinx.coroutines.CoroutineScope

/**
 * 根view，主要是放置符合设计的布局样式
 */
class ExoRootView : FrameLayout, IExoPlayerView {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    val binding = ViewExoPlayerRootBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        binding.ivBack.setOnClickListener {
            (context as Activity).finish()
        }
    }

    private var config: ExoPlayerViewConfig<IExoPlayerMode>? = null

    override fun needPlayerListener(): Boolean {
        return true
    }

    override fun onModelState(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        state: IPlayer.ModelState
    ) {
        super.onModelState(player, state)
        keepScreenOn = player.isPlaying
    }

    override fun onError(player: IPlayer<MediaItem, IExoPlayerMode>, error: Throwable) {
        super.onError(player, error)
        binding.tvError.visible()
        binding.tvError.text = error.cause?.message ?: error.message
        binding.tvError.setOnClickListener {
            binding.tvError.invisible()
            player.retry()
        }
    }

    override suspend fun onPrepareModel(
        scope: CoroutineScope,
        player: IPlayer<MediaItem, IExoPlayerMode>,
        model: IExoPlayerMode
    ) {
        super.onPrepareModel(scope, player, model)
        binding.tvError.invisible()
    }

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        this.config = config
    }

    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        this.config = null
    }
}